package com.mfc.education.service.edu.listener;

import com.alibaba.csp.sentinel.util.IdUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mfc.education.service.base.config.MybatisPlusConfig;
import com.mfc.education.service.edu.entity.Subject;
import com.mfc.education.service.edu.entity.excel.ExcelSubjectData;
import com.mfc.education.service.edu.mapper.SubjectMapper;
import com.mfc.education.service.edu.service.SubjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.commons.util.IdUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author mfc
 * @since 2021/9/5
 */
@Slf4j
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {


    private SubjectMapper subjectMapper;

    public ExcelSubjectDataListener() {

    }

    public ExcelSubjectDataListener(SubjectMapper subjectMapper) {
        this.subjectMapper = subjectMapper;
    }

    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {

        String levelOneTitle = excelSubjectData.getLevelOneTitle();
        String levelTwoTitle = excelSubjectData.getLevelTwoTitle();

        String parentId = "";
        Subject subjectLevelOne = isContainOneTitle(levelOneTitle);
        if (subjectLevelOne == null) {
            Subject subject = new Subject();
            subject.setTitle(levelOneTitle);
            subject.setParentId("0");
            subjectMapper.insert(subject);
            parentId = subject.getId();
        } else {
            parentId = subjectLevelOne.getId();
        }
        if (isContainTwoTitle(levelTwoTitle, parentId) == null) {

            Subject subject = new Subject();
            subject.setTitle(levelTwoTitle);
            subject.setParentId(parentId);
            subjectMapper.insert(subject);
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("保存剩余数据");
    }

    private Subject isContainOneTitle(String title) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", "0");
        return subjectMapper.selectOne(queryWrapper);
    }

    private Subject isContainTwoTitle(String title, String parentId) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", parentId);
        return subjectMapper.selectOne(queryWrapper);
    }
}
